<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="维修单号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入维修单号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="模具" prop="accountId">
        <el-select @change="handleQuery" clearable class="!w-240px" v-model="queryParams.accountId" placeholder="请选择模具"
          check-strictly filterable>
          <el-option v-for="dict in accountList" :key="dict.id" :label="dict.code" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="故障分类" prop="faultId">
        <el-select v-model="queryParams.faultId" placeholder="请选择故障分类Id" clearable class="!w-240px">
          <el-option v-for="cat in repaircategories" :key="cat.id" :label="cat.name" :value="cat.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="申请人" prop="applicantId">
        <el-select v-model="queryParams.applicantId" filterable clearable placeholder="请选择申请人" class="!w-240px">
          <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker v-model="queryParams.applicationTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <!--   <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mold:repair-job:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['mold:repair-job:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!--         <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['mold:repair-job:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange" border>
      <el-table-column type="selection" width="55" />
      <!--    <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="维修单号" align="center" prop="code">
        <template #default="scope">
          <el-button type="primary" link @click="openDetail(scope.row.id)">
            {{ scope.row.code }}
          </el-button>
        </template>
      </el-table-column>
      <!--       <el-table-column label="模具台账ID" align="center" prop="accountId" /> -->
      <el-table-column label="模具名称" align="center" prop="accountName" />
      <el-table-column label="模具编码" align="center" prop="accountCode" />
      <el-table-column label="维修分类" align="center" prop="repairCategoryName" />
      <el-table-column label="故障分类" align="center" prop="faultName" />
      <el-table-column label="申请人ID" align="center" prop="applicantName" />
      <el-table-column label="申请部门" align="center" prop="departName" />
      <el-table-column label="下达时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="接收时间" align="center" prop="jobReceiveTime" :formatter="dateFormatter" width="180px" />

      <el-table-column label="故障描述" align="center" prop="faultDescription" width="120">
        <template #default="scope">
          <div class="rich-text-content" v-html="scope.row.faultDescription"></div>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MOLD_REPAIR_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center" min-width="150px" fixed="right">
        <template #default="scope">
          <!--         <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['mold:repair-job:update']">
            编辑
          </el-button> -->

          <el-button link type="primary" @click="handleReceive(scope.row.id)" v-if="scope.row.status === 2">
            接收
          </el-button>
          <!--   <el-button link type="primary" @click="handleStartJob(scope.row.id)" v-if="scope.row.status === 3">
            开始作业
          </el-button> -->
          <el-button link type="primary" @click="handleWorkPort(scope.row.id)" v-if="scope.row.status === 3">
            报工
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mold:repair-job:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RepairJobForm ref="formRef" @success="getList" />

  <!-- 表单弹窗：报工界面 -->
  <RepairJobWorkPort ref="workPortRef" @success="getList" />

  <!-- 表单弹窗：详情界面 -->
  <RepairJobDetail ref="detailRef" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { RepairJobApi, RepairJob, RepairJobModStatus } from '@/api/mold/repairjob'
import RepairJobForm from './RepairJobForm.vue'
import RepairJobWorkPort from './RepairJobWorkPort.vue'
import RepairJobDetail from './RepairJobDetail.vue'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'
import { AccountApi } from '@/api/mold/account'
import { RepairFaultCategoryApi } from '@/api/mold/repairfaultcategory'

/** 模具维修任务 列表 */
defineOptions({ name: 'RepairJob' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<RepairJob[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  accountId: undefined,
  repairCategoryId: undefined,
  faultId: undefined,
  applicantId: undefined,
  departId: undefined,
  applicationTime: [],
  faultDescription: undefined,
  status: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const accountList = ref([])
const userList = ref<UserVO[]>([])
const repaircategories = ref()
const detailRef = ref() // 详情弹窗引用


const getRepaircategories = async () => {
  repaircategories.value = []
  const data = await RepairFaultCategoryApi.getRepairFaultCategoryAll()
  repaircategories.value = handleTree(data)
}


const getAccountList = async () => {
  accountList.value = []
  const data = await AccountApi.getAccountAll()
  accountList.value = data
}
const getUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RepairJobApi.getRepairJobPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const workPortRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RepairJobApi.deleteRepairJob(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除模具维修任务 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await RepairJobApi.deleteRepairJobList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: RepairJob[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RepairJobApi.exportRepairJob(queryParams)
    download.excel(data, '模具维修任务.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getRepaircategories()
  getUserList()
  getAccountList()
  getList()
})

//接收
const handleReceive = (id: number) => {
  const status_a: RepairJobModStatus = {
    id: id,
    status: 3,
    data: "" // 3为"已接收（维修中）"状态，具体值请根据实际业务调整
  }
  modStatus(status_a)
}

//开始作业
const handleStartJob = (id: number) => {
  //弹窗提醒：开始作业后，将会记录当前时间为作业开始时间，是否确定？
  message.confirm('确认开始作业吗？').then(() => {
    const status_a: RepairJobModStatus = {
      id: id,
      status: 4,
      data: "" // 4为"已开始作业"状态，具体值请根据实际业务调整
    }
    modStatus(status_a)
  })
}

// 打开报工界面
const handleWorkPort = (id: number) => {
  workPortRef.value.open(id)
}

// 打开详情界面
const openDetail = (id: number) => {
  detailRef.value.open(id)
}




/** 调用状态接口 */
const modStatus = async (s: RepairJobModStatus) => {
  try {
    await RepairJobApi.modStatus(s)
    message.success('操作成功')
    await getList()
  } catch (error) {
    message.error('操作失败')
    // 可选：console.error(error)
  }
}

</script>